package com.recharge.sup.impl;

import com.recharge.OrderService;
import com.recharge.domain.TradeFlow;
import com.recharge.domain.TradeOrder;
import com.recharge.mapper.ITradeOrderMapper;
import com.recharge.sup.AbsSupChargeService;
import com.recharge.utils.HttpClientUtils;
import com.recharge.utils.ProcessResult;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by CAOQI on 2016/12/17.
 *
 * 云流量 全国漫游口子
 */
@Service
public class YunLiuLiangChargeServiceImpl extends AbsSupChargeService {

    @Value("${yunliuliang.callBackUrl}")
    private String callBackUrl ;

    @Value("${yunliuliang.requestUrl}")
    private String requestUrl;

    @Value("${yunliuliang.yunllId}")
    private String yunllId;

    @Value("${yunliuliang.md5Key}")
    private String md5Key;

    @Value("${yunliuliang.supId}")
    private String supUid;

    @Value("${yunliuliang.channelId}")
    private String channelId;

    @Autowired
    private OrderService orderService;
    
    @Autowired
    private ITradeOrderMapper iTradeOrderMapper;

    private Logger logger = LoggerFactory.getLogger(getClass());


    public ProcessResult query(TradeOrder tradeOrder,TradeFlow tradeFlow){
        ProcessResult processResult = new ProcessResult();

        String serialId = tradeFlow.getSerialId()+"_"+tradeOrder.getGetCount();
        String sign = DigestUtils.md5Hex("query" + yunllId + serialId + md5Key);

        String sendData = "service=query&merchant_id=" + yunllId + "&merchant_orderid=" + serialId
                + "&sign=" + sign;
        logger.info("serialId: {} 发送给上游查询，请求参数:{}",serialId,sendData);
        String result = null;
        try {
            result = HttpClientUtils.invokeGetHttp(requestUrl+ "?" + sendData,"utf-8", 3000);
        } catch (Exception e2) {
            logger.error("查询订单信息出错",e2);
        }
        logger.info("serialId: {} ,收到上游返回数据, responseData={}",tradeFlow.getSerialId() , result);

        String result_desc = null;
        if (result != null && !"".equals(result)) {
            Map<String, String> rspMap = getMapParamter(result);
            // String orderId = "";
            String code = rspMap.get("result_code");
            result_desc = rspMap.get("result_desc");

            //修改订单处理状态为2（发送失败）
            iTradeOrderMapper.updateProcessStatus(tradeOrder.getOrderId(),result_desc);

            if ("0000".equals(code)) {
                code = rspMap.get("chargestatus");
                if (StringUtils.equals("SUCC",code)){
                    processResult.setCode(ProcessResult.SUCCESS);
                }else if (StringUtils.equals("1100",code)||
                        StringUtils.equals("1101",code)||
                        StringUtils.equals("1102",code)||
                        StringUtils.equals("1103",code)||
                        StringUtils.equals("1104",code)||
//                        StringUtils.equals("1105",code)||
                        StringUtils.equals("1106",code)||
                        StringUtils.equals("1107",code)||
                        StringUtils.equals("1108",code)||
                        StringUtils.equals("1109",code)||
                        StringUtils.equals("1110",code)||
                        StringUtils.equals("1111",code)||
                        StringUtils.equals("1112",code)||
                        StringUtils.equals("FAIL",code)){
                    processResult.setCode(ProcessResult.FAIL);
                }else{
                    processResult.setCode(ProcessResult.UNKNOWN);
                }
                return processResult;
            }else if (StringUtils.equals("1100",code)||
                    StringUtils.equals("1101",code)||
                    StringUtils.equals("1102",code)||
                    StringUtils.equals("1103",code)||
                    StringUtils.equals("1104",code)||
//                    StringUtils.equals("1105",code)||
                    StringUtils.equals("1106",code)||
                    StringUtils.equals("1107",code)||
                    StringUtils.equals("1108",code)||
                    StringUtils.equals("1109",code)||
                    StringUtils.equals("1110",code)||
                    StringUtils.equals("1111",code)||
                    StringUtils.equals("1112",code)||
                    StringUtils.equals("FAIL",code)){
                processResult.setCode(ProcessResult.FAIL);
                return processResult;
            }
        }

        processResult.setCode(ProcessResult.UNKNOWN);
        return  processResult;
    }

    @Override
    public ProcessResult recharge(TradeOrder tradeOrder , TradeFlow tradeFlow) {
        String chargeNumber = tradeOrder.getChargeNumber();
        Long chargeMoney = tradeOrder.getChargeMoney();
        String serialId = tradeFlow.getSerialId()+"_"+tradeOrder.getGetCount();;
        String busiType = tradeOrder.getBusiType()+"";
        String packageType = tradeOrder.getPackageType();
        String orderid = tradeOrder.getOrderId();
        busiType = "4";

        String sign = DigestUtils.md5Hex("order" + yunllId + serialId + chargeNumber + chargeMoney + busiType
                + callBackUrl +md5Key);

        String sendData = "service=order&merchant_id=" + yunllId + "&merchant_orderid=" + serialId
                + "&charge_number=" + chargeNumber + "&charge_money=" + chargeMoney + "&busi_type=" + busiType
                + "&back_url=" + callBackUrl + "&sign=" + sign+"&package_type="+packageType;

        String result = null;
        try {
            logger.info("orderid:{}, 发送云流量全国漫游请求：{}",tradeOrder.getOrderId(),requestUrl + "?" + sendData);
            result = HttpClientUtils.invokeGetHttp(requestUrl + "?" + sendData, "utf-8", 3000);
        } catch (Exception e) {
            logger.error("调用云流量接口异常",e);
        }

        logger.info("orderId:{},收到云流量返回:{}",tradeOrder.getOrderId(),result);

        String result_desc = null;
        if (result != null && !"".equals(result)) {
            Map<String, String> rspMap = getMapParamter(result);
            String orderId = "";
            String code = rspMap.get("result_code");
            result_desc = rspMap.get("result_desc");

            iTradeOrderMapper.updateProcessStatus(orderid,result_desc);
            if ("0000".equals(code)) {
                orderId = rspMap.get("orderid");
                logger.info("orderid : {}发送成功 . yll orderId:{}",tradeOrder.getOrderId(),orderId);
                ProcessResult processResult = new ProcessResult();
                processResult.setCode(ProcessResult.SUCCESS);
                return processResult;
            }else if (StringUtils.equals("1106",code)){
                            orderId = rspMap.get("orderid");
                            logger.info("orderid : {}发送失败. yll orderId:{}",tradeOrder.getOrderId(),orderId);
                            ProcessResult processResult = new ProcessResult();
                            processResult.setCode(ProcessResult.FAIL);
                            return processResult;
            }
        }
        logger.info("orderId:{}发送结果可疑", serialId);
        ProcessResult processResult = new ProcessResult();
        processResult.setCode(ProcessResult.UNKNOWN);
        return processResult;
    }


    @Override
    public void response(TradeOrder tradeOrder, TradeFlow tradeFlow,Map<String,String> responseMap) {
    	//修改订单处理状态为3（回调过）
        String orderid = tradeOrder.getOrderId();
        iTradeOrderMapper.updateProcessStatus(orderid,"收到结果");
    	
        String errorCode = responseMap.get("errorCode");
        if (StringUtils.equals("SUCC",errorCode)){

            orderService.SUCCESS(tradeOrder,tradeFlow);
        }else if (StringUtils.equals("FAIL",errorCode)||
                StringUtils.equals("1103",errorCode)||
                StringUtils.equals("1107",errorCode)||
                StringUtils.equals("1100",errorCode)||
                StringUtils.equals("1108",errorCode)||
                StringUtils.equals("1101",errorCode)||
                StringUtils.equals("1102",errorCode)||
                StringUtils.equals("1110",errorCode)||
                StringUtils.equals("1106",errorCode)||
                StringUtils.equals("1109",errorCode)||
                StringUtils.equals("1112",errorCode)||
                StringUtils.equals("1104",errorCode)){
            orderService.FAIL(tradeOrder, tradeFlow);
        }else{
            orderService.UNKNOWN(tradeOrder, tradeFlow);
        }
    }

    public static Map<String,String> getMapParamter(String paramter){
        Map<String,String> map = new HashMap<String,String>();
        String[] splitparam = paramter.split("\\&");
        for(int i=0; i<splitparam.length; i++){
            String[] splitpm = splitparam[i].split("=");
            if(splitpm.length<2){
                map.put(splitpm[0], "");
            }else{
                map.put(splitpm[0], splitpm[1]);
            }
        }
        return map;
    }
}
